<template>
  <div>
    <el-dialog
      title="公共聊天室"
      :visible="publicChatRoomVisible"
      width="50%"
      center
      append-to-body
      :modal="false"
      :close-on-click-modal="false"
      :show-close="false"
    >
      <!-- 头部提示 -->
      <div class="chat-room-header-title">
        <span>当前聊天内容只会存储一天哦,请大家文明交流</span>
      </div>
      <!-- 聊天室内部 -->
      <div class="chat-room">
        <div class="chat-left">
          <!-- 用户信息展示 -->
          <div style="text-align: center">
            <div class="user-avatar">
              <img :src="userInfo.loginUrlAvatar" alt="" />
            </div>
            <el-button size="mini" @click="closeChatRoom" round
              >退出聊天室</el-button
            >
          </div>
        </div>
        <!-- 聊天室内容主体 -->
        <div class="chat-main" id="chatMain">
          <div class="chat-content">
            <ul id="chatContent">
              <!-- 判断是否是自己发的还是别人发的, 根据id 和 leftOrRight  0 自己 1 对方 -->
              <li
                :class="
                  message.userId === userInfo.uid
                    ? 'my-message'
                    : 'other-message'
                "
                v-for="(message, index) in sendAndAcceptMessage"
                :key="index"
                ref="messageRef"
              >
                <div class="user-avatar" v-if="message.avatar">
                  <img :src="message.avatar" alt="" />
                </div>
                <div class="send-user-info" v-if="message.leftOrRight">
                  <div class="username">
                    <span>{{ message.username }}</span>
                    <div
                      class="message-content"
                      :class="
                        message.userId === userInfo.uid
                          ? 'my-label'
                          : 'other-label'
                      "
                    >
                      <span>{{ message.message }}</span>
                    </div>
                  </div>
                </div>
                <div class="onOrOff" v-if="message.onOrOff === 1">
                  {{ message.username }}加入了聊天室
                </div>
                <div class="onOrOff" v-if="message.onOrOff === 0">
                  {{ message.username }}退出了聊天室
                </div>
              </li>
              <div
                class="newMessage"
                @click="redirectNewMessage"
                v-if="getNewMessage"
              >
                <span class="prompt">您有一条新的消息</span>
                <span
                  class="close-prompt"
                  @click="getNewMessage = !getNewMessage"
                  >x</span
                >
              </div>
            </ul>
          </div>
        </div>
        <!-- 聊天室底部输入框 -->
        <div class="chat-footer">
          <div class="char-sendMessage-input">
            <el-input
              v-model="message"
              placeholder="请在这里输入你要发送的内容哦!回车发送内容~~"
              @keyup.enter.native="sendMessage"
            ></el-input>
            <div style="text-align: right">
              <el-button size="mini" @click="sendMessage">发送</el-button>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import BlogCommonApi from "@/api/BlogCommonApi";
const blogCommonApi = new BlogCommonApi();
export default {
  props: {
    publicChatRoomVisible: {
      default: false,
      type: Boolean,
    },
    publicChatRoom: {
      default: false,
    },
  },
  data() {
    return {
      userInfo: {},
      message: "",
      webSocket: null,
      showChat: false,
      sendAndAcceptMessage: [],
      userChatStatus: {},
      getNewMessage: false,
      sendCountDown: 0,
      onOrOff: false,
    };
  },
  methods: {
    closeChatRoom() {
      this.$emit("closeChatRoom", false);
      this.message = "";
    },
    sendMessage() {
      if (this.message.trim("").length === 0) {
        this.$message.warning("你还没有输入内容哦");
        return;
      }

      // type 0 为群发消息， type 1为单独发消息
      let sendMessageInfo = {
        message: this.message,
        avatar: this.userInfo.loginUrlAvatar,
        username: this.userInfo.nickname,
        leftOrRight: "0",
        userId: this.userInfo.uid,
        type: "0",
      };

      // 添加自己发送的消息数据
      let newMsgTop = document.getElementById("chatContent").offsetHeight;
      let top = document.documentElement.scrollTop;
      const timeTop = setInterval(() => {
        document.getElementById("chatMain").scrollTo(top, (top += 10000000));
        if (top >= newMsgTop) {
          clearInterval(timeTop); //清除定时器
        }
      }, 5);

      this.sendAndAcceptMessage.push(sendMessageInfo);

      this.$emit("sendPublicMsg", sendMessageInfo);
      //this.webSocket.send(JSON.stringify(sendMessageInfo));
      this.message = "";
    },
    // 连接websocket
    // openSocket() {
    //   if (typeof WebSocket === undefined) {
    //     this.$message.error("您的浏览器不支持聊天室功能哦,请更换浏览器");
    //   } else {
    //     // 初始化websocket
    //     //let url = "ws://110.40.213.24:6565/wsBlog/" + this.userInfo.uid;
    //     let url = "ws://localhost:9999/wsBlog/" + this.userInfo.uid;
    //     if (this.webSocket != null) {
    //       this.webSocket.close();
    //     }
    //     this.webSocket = new WebSocket(url);
    //     //初始化函数

    //     // 连接事件
    //     this.webSocket.onopen = () => {};

    //     //
    //     this.webSocket.onclose = () => {};

    //     this.webSocket.onerror = () => {
    //       console.log("websocket发生了错误");
    //     };
    //     //获取后端发送过来的消息信息, 进行处理
    //     this.webSocket.onmessage = (msg) => {
    //       this.sendAndAcceptMessage.push(JSON.parse(msg.data).chatRoom);
    //       if (JSON.parse(msg.data).newMsg) {
    //         this.getNewMessage = true;
    //       }
    //     };
    //   }
    // },
    redirectNewMessage() {
      this.getNewMessage = !this.getNewMessage;
      this.$nextTick(() => {
        const lastMessage =
          this.$refs.messageRef[this.$refs.messageRef.length - 1];
        lastMessage.scrollIntoView({ behavior: "smooth" });
      });
    },
  },
  mounted() {
    // 挂载websocket
    if (this.$store.state.isLogin) {
      this.userInfo = this.$store.state.userInfo;
      // this.openSocket();
      // 获取聊天记录
      blogCommonApi.getChatRoomRecord().then((res) => {
        res.data.forEach((m) => {
          let message = {
            message: m.content,
            avatar: m.avatar,
            username: m.username,
            leftOrRight: m.leftOrRight,
            userId: m.userId,
          };
          this.sendAndAcceptMessage.push(message);
        });
      });
    }
  },
  destroyed() {},
  watch: {
    publicChatRoomVisible(newVal) {
      this.showChat = newVal;
    },

    publicChatRoom(newVal) {
      // 获取后端发送过来的消息信息, 进行处理
      this.sendAndAcceptMessage.push(JSON.parse(newVal.data).chatRoom);
      if (JSON.parse(newVal.data).newMsg) {
        this.getNewMessage = true;
      }
    },
  },
};
</script>

<style scoped lang="scss">
img {
  width: 50px;
  height: 50px;
  border-radius: 50%;
}
.user-message {
  background-color: #c4c9d1;
}

.chat-main {
  overflow-y: scroll;
  overflow-x: none;
  height: 300px;
  background-color: #f6f6f6;
  .other-message {
    display: flex;

    .user-avatar {
      margin-top: 10px;
    }
    .send-user-info {
      margin-left: 10px;
    }
    .message-content {
      flex-wrap: wrap;
      margin-top: 5px;
      padding: 8px;
      border: 1px solid #c4c9d1;
      background-color: #fff;
    }
    .other-label {
      position: relative;
      background-color: inherit;
      font-size: 12px;
      border-radius: 4px;
    }
    .other-label:before {
      position: absolute;
      content: "";
      top: 7px;
      left: -5px;
      width: 0.6666em;
      height: 0.6666em;
      border-style: inherit;
      border-color: inherit;
      border-width: 0 0 1px 1px;
      transform: rotate(45deg);
      background-color: #f6f6f6;
      background-image: none;
      z-index: 2;
      transition: background 0.1s ease;
    }
  }
  .my-message {
    position: relative;
    display: flex;
    justify-content: flex-end;
    padding-right: 40px;
    margin-top: 10px;

    .user-avatar {
      position: absolute;
      top: 0;
      right: 0;
      margin-top: 10px;
    }
    .send-user-info {
      margin-right: 20px;
      .username {
        text-align: right;
      }
    }
    .message-content {
      flex-wrap: wrap;
      margin-top: 5px;
      padding: 8px;
      border: 1px solid #c4c9d1;
      background-color: #9eea6a !important;
    }
    .my-label {
      position: relative;
      background-color: inherit;
      font-size: 12px;
      border-radius: 4px;
    }
    .my-label:before {
      position: absolute;
      content: "";
      top: 7px;
      right: -5px;
      width: 0.6666em;
      height: 0.6666em;
      border-style: inherit;
      border-color: inherit;
      border-width: 1px 1px 0px 0px;
      transform: rotate(45deg);
      background-color: #9eea6a;
      background-image: none;
      z-index: 2;
      transition: background 0.1s ease;
    }
  }
  .newMessage {
    position: absolute;
    bottom: 36%;
    right: 4%;
    padding: 10px 0;
    background-color: #fff;
    cursor: pointer;
    user-select: none;
    z-index: 9999;
    .prompt {
      display: inline-block;
      color: #37c735;
      padding: 0 10px;
      border-right: 1px solid #d1d2d3 !important;
    }
    .close-prompt {
      padding: 0 10px;
    }
  }
}

.chat-main::-webkit-scrollbar {
  display: none;
}

::v-deep .el-input__inner {
  height: 100px;
  border: none;
}
.onOrOff {
  margin-left: 40%;
  font-size: 12px;
  text-align: center;
  color: #909294;
}
.chat-room-header-title {
  text-align: center;
  margin-bottom: 10px;
  color: red;
}
</style>
